import java.util.BitSet;




/**
 * This class contains methods to check errors because of bitwidth scaling
 * If result rounding is enable then it rounds result according to the bitwidth
 * entered by user. 
 * 
 * @author kspatel
 *
 */

 public class Bitwidth_Error_Check
{


//	public  boolean Error_Check(int input_data_to_check)
//	{
//		// Flag to indicate rounding error 
//		
//		boolean overflow_error = false;
//		
//		/*
//		 * If input data is negative then we will check weather the absolute value of
//		 * the input data for 2^bitwidth -1 and hence >= is used. 
//		 */
//		
//		if (input_data_to_check < 0)
//		{
//			if (((2^ISS_SIMD_Advance_Settings.user_entered_bitwidth)/2) >= Math.abs(input_data_to_check))
//				overflow_error = true;
//		}
//		
//		/*
//		 * If input data is positive then we will check weather the absolute value of
//		 * the input data for 2^bitwidth and hence > is used. 
//		 */
//
//		if (input_data_to_check>=0)
//		{
//			if (((2^ISS_SIMD_Advance_Settings.user_entered_bitwidth)/2) > Math.abs(input_data_to_check))
//				overflow_error = true;
//		}
//
//		return overflow_error; 
//	}
	
	public static int Round_Result(int input_data)
	{
		int rounded_data=input_data,difference;
		int rounding_index;
		String input_data_binary;
		BitSet temp = new BitSet();
		
		System.out.println(input_data);
//		difference = ((2^ISS_SIMD_Advance_Settings.user_entered_bitwidth)/2) - input_data;
		difference = ((int)Math.pow(2, 8)/2) - Math.abs(input_data);
		System.out.println("difference " + difference);
		
		rounding_index = (int)Math.ceil(Math.log10(Math.abs(difference))/Math.log10(2));
		//rounding_index = 5;
		System.out.println("rounding_index " + rounding_index);
		
		input_data_binary = Integer.toBinaryString(input_data);
		
		//rounded_data = input_data - ((int)Math.pow(2,rounding_index));
		
		//Taking the lower rounding_index bits.
		
//		input_data_binary = Integer.toBinaryString(input_data);
		System.out.println("Input in binary  " + input_data_binary);
		//temp = (BitSet)input_data;
		
		int b=0;
		String s;
		
		s = input_data_binary.substring(0,rounding_index-1);
		System.out.println("s=" + s);
//		for(int i=0;i<rounding_index;i++)
//			
//		{
//		//	if ((input_data && (Math.pow(2, i)))==1)
//			b = input_data_binary.codePointAt(i);		
//			System.out.println("b=" + b);
//			
//			//	rounded_data = input_data - (int)Math.pow(2,i);
//				
//		
//		}
		//b = Integer.parseInt(s);
		b= Integer.parseInt(s, 2);
		System.out.println("b= "+b);
		
		rounded_data = input_data - b;
		
		//rounded_data = input_data &  (int)(Math.pow(2,rounding_index));
		
		System.out.println("after  rounding " + rounded_data);
		return rounded_data;
	}
	
	
	public static void main(String args[])
	
	{
	
		int a = 182;
		Round_Result(a);
	}


}